package com.cenluan.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.jfinal.kit.StrKit;

public class OssManager {
	/**
	 * 客户端
	 */
	private static OSSClient client;
	/**
	 * 杭州数据服务中心，项目使用的数据服务中心
	 */
	private static String server;
	/**
	 * 图片bucket
	 */
	private static String imageBucket;
	/**
	 * 图片服务器域名
	 */
	private static String imageDomain;

	protected static void setClient(OSSClient client) {
		OssManager.client = client;
	}

	protected static void setServer(String server) {
		OssManager.server = server;
	}

	protected static void setImageBucket(String imageBucket) {
		OssManager.imageBucket = imageBucket;
	}

	protected static void setImageDomain(String imageDomain) {
		OssManager.imageDomain = imageDomain;
	}

	public static OSSClient getClient() {
		return client;
	}

	public static String getServer() {
		return server;
	}

	public static String getImageBucket() {
		return imageBucket;
	}

	public static String getImageDomain() {
		return imageDomain;
	}

	/**
	 * 保存图片
	 * 
	 * @param input
	 *            输入流
	 * @param metadata
	 *            元数据
	 * @param key
	 *            文件的唯一标识名称，可不包含后缀
	 */
	public static void saveImage(InputStream input, ObjectMetadata metadata,
			String key) {
		client.putObject(imageBucket, key, input, metadata);
	}

	/**
	 * 保存图片
	 * 
	 * @param file
	 * @param key
	 */
	public static void saveImage(File file, String key) {
		ObjectMetadata metadata = new ObjectMetadata();
		metadata.setContentLength(file.length());
		try {
			saveImage(new FileInputStream(file), metadata, key);
		} catch (FileNotFoundException e) {
			throw new IllegalArgumentException("file not found", e);
		}
	}

	/**
	 * 获取图片地址，获取后的地址通过拼接参数可实现压缩
	 * 
	 * @param key
	 * @return
	 */
	public static String getImageUrl(String key) {
		if (StrKit.isBlank(key)) {
			return null;
		}
		return "http://" + imageDomain + "/" + key;
	}

	/**
	 * 删除图片
	 * 
	 * @param key
	 */
	public static void deleteImage(String key) {
		if (StrKit.isBlank(key)) {
			return;
		}
		client.deleteObject(imageBucket, key);
	}

}
